package com.shwread.android.qysw.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.NewActionHelp;
import com.bumptech.glide.Glide;
import com.google.gson.reflect.TypeToken;
import com.shwread.android.qysw.bean.VoteMainBean;
import com.shwread.android.qysw10000000.R;
import com.shwread.android.ui.customview.MyListView;
import com.shwread.android.ui.widget.refresh.PullToRefreshScrollView;
import com.shwread.android.ui.widget.refresh.PullToRefreshUtil;
import com.shwread.android.ui.widget.refresh.base.PullToRefreshBase;
import com.shwread.http.base.ObjectHttpResponseHandler;

import org.apache.http.Header;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

public class VoteMainActivity extends
        BaseBusinessActivity {


    private RelativeLayout empty;
    private TextView tvTitle;
    private ImageView ivPersion;
    private View loadingView;
    private ImageView loadingImg;
    private AnimationDrawable animationDrawable;
    private PullToRefreshScrollView refreshView;
    private MyListView lv;
    private Button common_header_back;
    private int pageNum = 1;
    private final int LENGTH = 10;
    private List<VoteMainBean.ActivityVotingBean> activityVotingBeanList;
    private VoteMainAdapter adapter;
    private boolean isHasMore = true;

    private int screenW = 0;
    private int dp_15 = 0;
    private int imgWidth = 0;


    @Override
    public Handler getUIHandler() {
        return null;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_vote_main);
        initViews();
    }

    private void initViews() {
        WindowManager wm = this.getWindowManager();
        screenW = wm.getDefaultDisplay().getWidth();
        dp_15 = dip2px(15);
        activityVotingBeanList = new ArrayList<>();
        lv = (MyListView) findViewById(R.id.lv);
        refreshView = (PullToRefreshScrollView) findViewById(R.id.refreshView);
        PullToRefreshUtil.initLabel(this, refreshView);
        refreshView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ScrollView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ScrollView> refreshView) {
                if (refreshView.isHeaderShown()) {
                    pageNum = 1;
                    qryVotingList(pageNum, LENGTH);
                } else if (refreshView.isFooterShown()) {
                    if (isHasMore) {
                        pageNum++;
                        qryVotingList(pageNum, LENGTH);
                    } else {
                        PullToRefreshUtil.setLoadLabel(refreshView, "没有更多数据了");
                        refreshView.onRefreshComplete();
                    }
                }
            }
        });
        empty = (RelativeLayout) findViewById(R.id.empty);
        tvTitle = (TextView) findViewById(R.id.common_header_name);
        String titStr = getIntent().getStringExtra("title");
        if (TextUtils.isEmpty(titStr)) {
            tvTitle.setText("投票调研");
        } else {
            tvTitle.setText(titStr);
        }
        ivPersion = (ImageView) findViewById(R.id.common_header_persion);
        ivPersion.setVisibility(View.GONE);
        common_header_back = (Button) findViewById(R.id.common_header_back);
        common_header_back.setVisibility(View.VISIBLE);

        loadingView = findViewById(R.id.common_loading_layout);
        loadingImg = (ImageView) findViewById(R.id.common_loading__img);

        common_header_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent = new Intent(VoteMainActivity.this, VoteDetailActivity.class);
                intent.putExtra("voteBean", activityVotingBeanList.get(i));
                startActivity(intent);
            }
        });
        adapter = new VoteMainAdapter(VoteMainActivity.this, activityVotingBeanList);
        lv.setAdapter(adapter);
        qryVotingList(pageNum, LENGTH);
    }


    class VoteMainAdapter extends BaseAdapter {

        private Context context;
        private List<VoteMainBean.ActivityVotingBean> list;

        public VoteMainAdapter(Context context, List<VoteMainBean.ActivityVotingBean> list) {
            this.context = context;
            this.list = list;
            imgWidth = screenW - 2 * dp_15;
        }

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int i) {
            return list.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            ViewHolder h = null;
            if (view == null) {
                h = new ViewHolder();
                view = LayoutInflater.from(context).inflate(R.layout.item_lv_vote_main, null);
                h.tvTitleVoteMain = (TextView) view.findViewById(R.id.tvTitleVoteMain);
                h.tvStatuVoteMain = (TextView) view.findViewById(R.id.tvStatuVoteMain);
                h.tVDescVoteMain = (TextView) view.findViewById(R.id.tVDescVoteMain);
                h.iVIconVoteMain = (ImageView) view.findViewById(R.id.iVIconVoteMain);
                view.setTag(h);
            } else {
                h = (ViewHolder) view.getTag();
            }
            LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) h.iVIconVoteMain.getLayoutParams();
            lp.width = imgWidth;
            lp.height = (imgWidth / 16) * 9;
            h.iVIconVoteMain.setLayoutParams(lp);
            VoteMainBean.ActivityVotingBean activityVotingBean = list.get(i);
            h.tvTitleVoteMain.setText(activityVotingBean.getTitle());
            //1---》未开始  2---》进行中    3---》已结束    状态1不展示，后台不会返回
            if (activityVotingBean.getVotingStatus() == 2) {
                h.tvStatuVoteMain.setTextColor(Color.parseColor("#e22b36"));
                h.tvStatuVoteMain.setText("进行中");
            } else if (activityVotingBean.getVotingStatus() == 3) {
                h.tvStatuVoteMain.setTextColor(Color.parseColor("#b1b1b1"));
                h.tvStatuVoteMain.setText("已结束");
            } else {
                h.tvStatuVoteMain.setText("");
            }
            //1---》文本  2---》图片    3---》视频    事实上列表页只展示图片和文本，视频的也是展示个缩略图
            h.tVDescVoteMain.setText(activityVotingBean.getVotingDescription());
            if (activityVotingBean.getVotingFashion() == 1) {
                h.iVIconVoteMain.setVisibility(View.GONE);
            } else {
                h.iVIconVoteMain.setVisibility(View.VISIBLE);
                Glide.with(context)
                        .load(activityVotingBean.getCoverPhoto())
                        .placeholder(R.drawable.bg_big_image)
                        .into(h.iVIconVoteMain);
            }
            return view;
        }

        class ViewHolder {
            TextView tvTitleVoteMain;
            TextView tvStatuVoteMain;
            TextView tVDescVoteMain;
            ImageView iVIconVoteMain;
        }
    }


    /**
     * @param flag 0:加载中，1：加载完成，-1：加载失败
     */
    private void updateLoadingView(int flag) {
        switch (flag) {
            case -1:
                loadingView.setVisibility(View.VISIBLE);
                refreshView.setVisibility(View.GONE);
                if (animationDrawable != null && animationDrawable.isRunning()) {
                    animationDrawable.stop();
                }
                loadingImg.setBackgroundResource(R.drawable.home_loading_fail);
                break;
            case 0:
                loadingView.setVisibility(View.VISIBLE);
                refreshView.setVisibility(View.GONE);
                loadingImg.setBackgroundResource(R.drawable.home_progress);
                animationDrawable = (AnimationDrawable) loadingImg.getBackground();
                animationDrawable.start();
                break;
            case 1:
                loadingView.setVisibility(View.GONE);
                refreshView.setVisibility(View.VISIBLE);
                break;
        }
    }


    private void qryVotingList(final int pageNum, int length) {

        NewActionHelp.qryVotingList(this, pageNum, length, new ObjectHttpResponseHandler<VoteMainBean>() {
            @Override
            public void onFailure(int i, Header[] headers, String s, Throwable throwable) {
                Log.e("111111fail", "qryVotingList" + s);
                refreshView.onRefreshComplete();
                updateLoadingView(-1);
            }

            @Override
            public void onSuccess(int i, Header[] headers, VoteMainBean voteMainBean, String s) {
                Log.e("111111OK", "qryVotingList" + voteMainBean.toString());
                updateLoadingView(1);
                refreshView.onRefreshComplete();
                if (null == voteMainBean.getActivityVoting() || voteMainBean.getActivityVoting().size() == 0) {
                    isHasMore = false;
                    if (pageNum == 1) {
                        empty.setVisibility(View.VISIBLE);
                    }
                } else {
                    isHasMore = true;
                    if (pageNum == 1) {
                        activityVotingBeanList.clear();
                    }
                    activityVotingBeanList.addAll(voteMainBean.getActivityVoting());
                }
                adapter.notifyDataSetChanged();
            }

            @Override
            public Type getType() {
                return new TypeToken<VoteMainBean>() {
                }.getType();
            }
        });
    }

    public int dip2px(float dpValue) {
        final float scale = this.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }
}
